﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Ocmf.Types;

namespace Ocmf.Forms
{
    public partial class EditChamberForm : Form
    {
        private Chamber editChamber;
        
        public EditChamberForm()
        {
            InitializeComponent();
        }

        public EditChamberForm(Chamber chamber)
        {
            InitializeComponent();
            
            editChamber = chamber;
            
            ipAddressTextBox.Text = editChamber.IpAddress;
            chamberAliasTextBox.Text = editChamber.HostName;
        }

        private void ipAddressTextBox_Validating(object sender, CancelEventArgs e)
        {
            if (!Regex.Match(ipAddressTextBox.Text,
                            @"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b")
                    .Success)
                errorProvider.SetError(ipAddressTextBox, "Please enter a valid IP address");
            else
                errorProvider.SetError(ipAddressTextBox, "");
        }

        private void ChamberAlias_Validating(object sender, CancelEventArgs e)
        {
            if(editChamber.HostName != chamberAliasTextBox.Text && DatabaseProvider.Chambers.ContainsKey(chamberAliasTextBox.Text))
                errorProvider.SetError(chamberAliasTextBox,"Duplicated Chamber Alias");
            else
                errorProvider.SetError(chamberAliasTextBox,"");
        }

        private void okButton_Click(object sender, EventArgs e)
        {
            if (editChamber == null)
                DatabaseProvider.InsertChamber(new Chamber(0, chamberAliasTextBox.Text, ipAddressTextBox.Text, ChamberState.Error, DateTime.MinValue, null));
            else
            {
                editChamber.HostName = chamberAliasTextBox.Text;
                editChamber.IpAddress = ipAddressTextBox.Text;
                DatabaseProvider.UpdateChamber(editChamber);
            }

            DialogResult = DialogResult.OK;
        }

        private void cancelButton_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }
    }
}
